﻿using Brc_PaaS.Bll.System;
using Brc_PaaS.Common.Entity;
using Brc_PaaS.Common.Model.Basic;
using Brc_PaaS.Core.Redis;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace Brc_PaaS.Api.Common
{
    /// <summary>
    /// 基础控制器
    /// </summary>
    [ApiController]
    public class BaseController : ControllerBase
    {
        /// <summary>
        /// 配置读取接口
        /// </summary>
        private readonly IConfiguration configuration;
        private readonly ISystem _system;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="syetem"></param>
        public BaseController(IConfiguration configuration, ISystem syetem)
        {
            this.configuration = configuration;
            this._system = syetem;
        }
        private string systemId = string.Empty;
        private Bas_System _systemInfo = null;
        /// <summary>
        /// 系统Id
        /// </summary>
        protected string SystemId
        {
            get
            {
                if (string.IsNullOrEmpty(systemId))
                {
                    systemId = HttpContext.Items["appKey"] != null ? HttpContext.Items["appKey"].ToString() : string.Empty;
                }
                return systemId;
            }
        }

        /// <summary>
        /// 当前访问的业务系统信息
        /// </summary>
        protected Bas_System SystemInfo
        {
            get
            {
                if (_systemInfo == null)
                {
                    if (!string.IsNullOrEmpty(SystemId))
                    {
                        using (IRedisManager redisManager = new RedisManager(RedisServerEntity))
                        {
                            var dbSystemInfo = redisManager.GetOrFetchFromHash<Bas_System>($"System:{SystemId}", id => { return _system.GetSystem(SystemId).Data; });
                            if (dbSystemInfo.Status == 1)
                                _systemInfo = dbSystemInfo;
                        }
                    }
                }
                return _systemInfo;

            }
        }

        /// <summary>
        /// PaaS平台Redis配置实体
        /// </summary>
        protected RedisServerEntity RedisServerEntity
        {
            get
            {
                return configuration.GetSection("RedisConfiguration").Get<RedisServerEntity>();
            }
        }
    }

}

